#include <iostream>
#include <vector>
#include <unistd.h>
#include <pthread.h>

using namespace std;
#define NUM 4
struct threadData//给每个线程做标记
{
    string threadname;
};
__thread int a = 10;
// 所有的线程，执行的都是这个函数？
void *threadRoutine(void *args)
{
    threadData *td = static_cast<threadData *>(args);
    int i = 5;
    while (i)
    {
        cout << "我是" << td->threadname << ", pid: " << getpid() << endl;
        cout<<++a<<endl;
        sleep(1);
        i--;
    }

    delete td;
    return nullptr;
}

void InitThreadData(threadData *td, int number)
{
    td->threadname = "线程-" + to_string(number);
}

int main()
{
    // 创建多线程！
    vector<pthread_t> tids;
    for (int i = 0; i < NUM; i++)
    {
        pthread_t tid;
        threadData *td = new threadData;
        InitThreadData(td, i);//标记线程

        pthread_create(&tid, nullptr, threadRoutine, td);
        tids.push_back(tid);
    }
    //线程等待  
    for (int i = 0; i < tids.size(); i++)
    {
        pthread_join(tids[i], nullptr);
    }
    cout<<"主线程的a:"<<a<<endl;

    return 0;
}